<?php
class Talktangle_Api_Core extends Core_Api_Abstract
{
    const TANGLE_STATUS_NEW = 0;
    const TANGLE_STATUS_COMPLETED = 2;
    const TANGLE_STATUS_FAIL = 3;
    
    public $anphabetic = array(
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        'l',
        'm',
        'n',
        'o',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z'
    );
    
    private $fillWordMatricMethod = array(
         'fillWordMatricNext',
         'fillWordMatricBack',
         'fillWordMatricTop',
         'fillWordMatricDown',
         'fillWordMatricTLRB',
         'fillWordMatricBLTR',
         'fillWordMatricRTBL',
         'fillWordMatricRBTL'
    );
    
    public function initMatric($rowCount){
        $matric = array();
        for($i=0;$i<$rowCount;$i++){
            $matric[] = array();
        }
        return $matric;
    }
    
    public function fillWordMatricNext($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($col+$length > $max['col']) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row][$col+$i])){
                $oldvalue = $matric[$row][$col+$i];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$i]) {
                        return false;
                    }
                }
                
            }
        }
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row][$col+$i] = $word[$i];
            $sessionValue[$i] = $this->getIndexFromColRow($row,$col+$i);
        }
        $this->setCrossWord($id,$word,$sessionValue);
        return true;
    }
    
    public function fillWordMatricBack($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($col-$length < 0 ) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row][$col-$i])){
                $oldvalue = $matric[$row][$col-$i];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$length -$i -1]) {
                        return false;
                    }
                }
                
            }
        }
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row][$col-$i] = $word[$length -$i -1];
            $sessionValue[$length -$i -1] = $this->getIndexFromColRow($row,$col-$i);
        }
        $this->setCrossWord($id,$word,$sessionValue);
        return true;
    }    
    
    
    public function fillWordMatricDown($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($row+$length > $max['row']) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row +$i][$col])){
                $oldvalue = $matric[$row +$i][$col];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$i]) {
                        return false;
                    }
                }
                
            }
        }
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row+$i][$col] = $word[$i];
            $sessionValue[$i] = $this->getIndexFromColRow($row+$i,$col);
        }
        $this->setCrossWord($id,$word,$sessionValue);
        return true;
    }
    
    public function fillWordMatricTop($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($row-$length < 0 ) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row-$i][$col])){
                $oldvalue = $matric[$row-$i][$col];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$length -$i -1]) {
                        return false;
                    }
                }
                
            }
        }
        
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row -$i][$col] = $word[$length -$i -1];
            $sessionValue[$length -$i -1] = $this->getIndexFromColRow($row -$i,$col);
        }
        
        $this->setCrossWord($id,$word,$sessionValue);
        return true;
    }
    
    
    public function fillWordMatricTLRB($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($col+$length > $max['col']) return false;
        if($row+$length > $max['col']) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row+$i][$col+$i])){
                $oldvalue = $matric[$row+$i][$col+$i];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$i]) {
                        return false;
                    }
                }
                
            }
        }
        
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row+$i][$col+$i] = $word[$i];
            $sessionValue[$i] = $this->getIndexFromColRow($row+$i,$col+$i);
        }
        $this->setCrossWord($id,$word,$sessionValue);
        return true;
    }
    
    public function fillWordMatricBLTR($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($col+$length > $max['col']) return false;
        if($row - $length < 0) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row-$i][$col+$i])){
                $oldvalue = $matric[$row-$i][$col+$i];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$i]) {
                        return false;
                    }
                }
                
            }
        }
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row-$i][$col+$i] = $word[$i];
            $sessionValue[$i] = $this->getIndexFromColRow($row-$i,$col+$i);
            
        }
        $this->setCrossWord($id,$word,$sessionValue);
        
        
        return true;
    }
    
    public function fillWordMatricRTBL($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($col-$length > $max['col']) return false;
        if($row+$length > $max['col']) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row+$i][$col-$i])){
                $oldvalue = $matric[$row-$i][$col-$i];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$length -$i -1]) {
                        return false;
                    }
                }
                
            }
        }
        
        
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row+$i][$col-$i] = $word[$length -$i -1];
            $sessionValue[$length -$i -1] = $this->getIndexFromColRow($row+$i,$col-$i);
        }
        $this->setCrossWord($id,$word,$sessionValue);
        return true;
    }
    
    public function fillWordMatricRBTL($id,$word,&$matric,$point,$max){
        $col = $point['col'];
        $row = $point['row'];
        
        $length = strlen($word);
        if($col-$length > $max['col']) return false;
        if($row - $length < 0) return false;
        
        $ok = true;
        for($i=0 ;$i<$length;$i++){
            if(isset($matric[$row-$i][$col-$i])){
                $oldvalue = $matric[$row-$i][$col-$i];
                if(!empty($oldvalue)) {
                    if($oldvalue != $word[$length -$i -1]) {
                        return false;
                    }
                }
                
            }
        }
        
        $sessionValue = array();
        for($i =0; $i<$length;$i++){
            $matric[$row-$i][$col-$i] = $word[$length -$i -1];
            
            $sessionValue[$length -$i -1] = $this->getIndexFromColRow($row-$i,$col-$i);
        }
        $this->setCrossWord($id,$word,$sessionValue);
        return true;
    }
    
    public function crossCharacters($characters,$crossId){
        $settingApi = Engine_Api::_()->getApi('settings','core');
        $rowCount =   $settingApi->getSetting('talktangle.cross.rowcount',15);//15;
        $colCount = $settingApi->getSetting('talktangle.cross.colcount',15);//15;
        $maxtricCell = $colCount*$rowCount;
        
        $matric = $this->initMatric($rowCount);
        
        $characters = trim($characters);
        $characters = explode(' ',$characters);
        foreach($characters as $key => $value){
            $ok = false;
            while($ok == false){
                $methodIndex = mt_rand(0,7);
                $point = mt_rand(0,$maxtricCell-1);
                
                $methodName = $this->fillWordMatricMethod[$methodIndex];
                $ok = $this->$methodName($crossId,$value,$matric,$this->getColRow($point,$colCount));
                
            }
            
        }
        $cross_session = new Zend_Session_Namespace('cross_session');
        $cross_session->matric = $matric;
        return $matric;
    }
    
    private function setCrossWord($id,$key,$value){
        
        $cross_session = new Zend_Session_Namespace('cross_session');
        $data = $cross_session->data;
        $data[$id][$key] = $value;
        $cross_session->data = $data;
    }
    private function validCrossWord($id,$key,$answer){
        $cross_session = new Zend_Session_Namespace('cross_session');
        $data = $cross_session->data;
        
        if(!isset($data[$id])) return false;
        $data = $data[$id];
        
        if(!isset($data[$key])) return false;
        $values = $data[$key];
        
        $t = explode('-',$answer);
        $a = array();
        foreach($t as $ke => $value){
            if(!empty($value) && $value !=' '){
                $a[] = $value; 
            }
        }
        
        foreach($values as $k => $value){
            if($a[$k] != $value) return false;
        }
        
        return true;
    }
    
    
    private function getColRow($value,$columCount){
        
        $row = intval($value/$columCount);
        $col = $value % $columCount;
        return array('row' => $row,'col'=>$col);
    }
    
    private function getIndexFromColRow($row,$col){
        $settingApi = Engine_Api::_()->getApi('settings','core');
        $colCount = $settingApi->getSetting('talktangle.cross.colcount',15);//15;
        return $row*$colCount +$col;
    }
    
    public function unCrosstangle($answer ,$crossId){
        foreach($answer  as $key => $value){
            $ok = $this->validCrossWord($crossId,$key,$value);
            if($ok == false) return false;
        }
        
        return true;
    }


/*
$tangle->getIdentity();
$tangle->getTangleType();
$tangle->getOwner();
$tangle->getTangleItemType();
*/
    public function untangleNotification($tangle,$winner){
                        
        // have to create below functions before
        $tangle_id = $tangle->getIdentity();
        $tangle_type = $tangle->getTangleType();
        $tangleOwner = $tangle->getOwner();
    
        //select competed user from history
        $historyTable = Engine_Api::_()->getDbtable('history','talktangle');
        $notifyUserIds = $historyTable->select()
                            ->distinct(true)
                            ->from($historyTable->info('name'),'user_id')
                            ->where('object_id = ?',$tangle_id)
                            ->where('object_type = ?',$tangle_type)                          
                            ->query()
                            ->fetchAll(Zend_Db::FETCH_COLUMN)
                            ;
    
        // notify to owner and competed user            
        
        $userTable = Engine_Api::_()->getItemTable('user');
        $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');        
    
        foreach( $userTable->find($notifyUserIds) as $notifyUser ) {
            // Don't notify self
            if( $notifyUser->isSelf($winner) ) {
              continue;
            }
            
            if( $notifyUser->isSelf($tangleOwner) ) {
              $type = 'talktangle_untangle_response';
            } else {
              $type = 'talktangle_untangle_reply';
            }
            
            $notifyApi->addNotification($notifyUser, $winner, $tangle, $type, array(
              'type' => $tangle_type
            ));
        }        
    }
    
    //add point for creater or winner
    public function addPoint($user, $points){
        
        if(!($user instanceof User_Model_User)){
            return;
        }
        $db = Engine_Db_Table::getDefaultAdapter();
        $db->beginTransaction() ;
        try{
            
            $user->points =  $user->points + $points;
            $user->save();
            
            $db->commit();                
        }   
        catch(Exception $e){
            $db->rollBack();
            throw $e;
        }                 
        
    }
    
    //check tangle status
    //return true if Un-tangle
    public function checkTangle($tangle){ 
        if(!empty($tangle->winner_id)) return false;
        return true;
    }
    
    public function setStatus($tangle,$status = self::TANGLE_STATUS_NEW){
        $tangle->status = $status;
    }
    
    public function getUserType($user){
        //return 'company';
        return $user->type;
    }
    
    public function getAds($params){
        return array(
            array(
                'id' => '1',
                'url' => 'url',
                'des' => 'des'
            )
        );
    }
    
    public function createBuyNowTransaction($plugin, $ads,  array $params = array()) {
//    	$priceLevelEnabled = $deal->pricelevel_enabled;

    	$params['driverSpecificParams']['PayPal'] = array(
                'AMT' => $params['price'],
                'DESC' => $params['description'],
                'CUSTOM' => $ads->ad_id,
                'INVNUM' => $params['vendor_order_id'],
                'ITEMAMT' => $params['price'],
                'ITEMS' => array(
                        array(
                                'NAME' => $ads->title,
                                'DESC' => $params['description'],
                                'AMT' => 5,
                                'NUMBER' => $ads->ad_id,
                                'QTY' => $params['amount'],
                        ),
                )
        );
//    	echo "<pre>";
//        print_r($params['driverSpecificParams']['PayPal']);
//        die;        
//    	if ($priceLevelEnabled) {
//    		$priceRange = $deal->findPriceRange($params['amount']);
//    		
//    		// Must have price levels
//	    	if (!empty($priceRange) && $priceRange !== false && is_array($priceRange) && count($priceRange) > 0) {
//	    		$items = array();
//	    		$total = 0;
//	    		foreach ($priceRange as $price) {
//	    			$items[] = array(
//	    				'NAME' => $groupon->title, 
//						'DESC' => $params['description'], 
//						'AMT' => $price['price'], 
//						'NUMBER' => $deal->deal_id, 
//						'QTY' => $price['quantity']
//	    			);
//	    			$total += $price['quantity'] * $price['price'];
//	    		}
//	    		$params['driverSpecificParams']['PayPal']['ITEMS'] = $items;
//	    		$params['driverSpecificParams']['PayPal']['AMT'] = $total;
//	    		unset($params['driverSpecificParams']['PayPal']['ITEMAMT']);
//	    	}
//    	}
        // Create transaction
        $transaction = $plugin->createTransaction($params);
        return $transaction;
    }
    
    
    public function getPromotionSelect($user = null ){
        
        if (empty($user) || is_null($user)) {
            $user = Engine_Api::_()->user()->getViewer();
            if (!$user) return null;
            
        } 
        
        $networkTable = Engine_Api::_()->getDbtable('membership', 'network');
        $networkIds = $networkTable->getMembershipsOfIds($user);
        $networkIds = array_unique($networkIds);
        
        $userInNetworks = array();
        $userInNetworksObject = array();
        if (!empty($networkIds)) {
            $select  = $networkTable->select()
                                       ->where('resource_id  in (?)',$networkIds)
                                       ->where('user_id <> ?', $user->user_id);
                                   
            $userInNetworksObject = $networkTable->fetchAll($select);
            foreach($userInNetworksObject as $user){
                $userInNetworks[] = $user->user_id;
            } 
        }
        
        $followT = Engine_Api::_()->getDbtable('followers','talktangle');
        $followIds = $followT->getSubscriber($user->user_id);
        
        $ids = array_merge($userInNetworks,$followIds);
        $ids = array_unique($ids);
        
        if (!empty($ids)) {
            $promotionT = Engine_Api::_()->getDbtable('promotions','talktangle');
            $select = $promotionT->select()-> where('owner_id in (?)',$ids);
            return $select;
            $promotions = $promotions->fetchAll($select);
            return $promotions;
        }
        
        return null;
        
        
    }    
    
    
    public function postTwitter($params){
        $publishMessage = html_entity_decode($params['body'].' '.$params['link']);
        try {
          $twitterTable = Engine_Api::_()->getDbtable('twitter', 'user');
          if( $twitterTable->isConnected() ) {
            // @todo truncation?
            // @todo attachment
            $twitter = $twitterTable->getApi();
            $twitter->statuses->update($publishMessage);
          }
        } catch( Exception $e ) {
          throw $e;
        }
    }
    public function postFacebook($params){
        $viewer = Engine_Api::_()->user()->getViewer();
        $publishMessage = html_entity_decode($params['body']);
        try {

          $facebookTable = Engine_Api::_()->getDbtable('facebook', 'user');
          $facebook = $facebookApi = $facebookTable->getApi();
          $fb_uid = $facebookTable->find($viewer->getIdentity())->current();

          if( $fb_uid &&
              $fb_uid->facebook_uid &&
              $facebookApi &&
              $facebookApi->getUser() &&
              $facebookApi->getUser() == $fb_uid->facebook_uid ) {
            $fb_data = array(
              'message' => $publishMessage,
            );
            if( isset($params['link']) ) {
              $fb_data['link'] = $params['link'];
            }
            if( isset($params['name']) ) {
              $fb_data['name'] = $params['name'];
            }
            if( isset($params['description']) ) {
              $fb_data['description'] = $params['description'];
            }
            if( isset($params['picture']) ) {
              $fb_data['picture'] = $params['picture'];
            }
            $res = $facebookApi->api('/me/feed', 'POST', $fb_data);
          }
        } catch( Exception $e ) {
          throw $e;
        }
    }


    public function continueProcessBuy($tangle,$type,$ads,$form) {
    	
        $user = Engine_Api::_()->user()->getViewer();
        // Get gateway
        $gatewayId = 2;	//Always is PayPay
        if( !$gatewayId ||
                !($gateway = Engine_Api::_()->getItem('payment_gateway', $gatewayId))
               ) {
            return $form->addError(Zend_Registry::get('Zend_Translate')->_('Paypal is disabled. Please contact to administrator for more details'));
        }
        $this->view->gateway = $gateway;

		if(!($gateway->enabled)){
			return $form->addError(Zend_Registry::get('Zend_Translate')->_('Paypal is disabled. Please contact to administrator for more details'));
		}
    		
		//Get Currency of Groupon
		$paypalConfig = (array)$gateway->config;
        $paypalConfig['testMode'] =  $gateway->test_mode;

    	$plugin =  new Talktangle_Plugin_Gateway_PayPal((array)$paypalConfig);        

        // Create order
        $ordersTable = Engine_Api::_()->getDbtable('orders', 'payment');
        if( !empty($this->_session->order_id) ) {
            $previousOrder = $ordersTable->find($this->_session->order_id)->current();
            if( $previousOrder && $previousOrder->state == 'pending' ) {
                $previousOrder->state = 'incomplete';
                $previousOrder->save();
            }
        }

        $ordersTable->insert(array(
                'user_id' => Engine_Api::_()->user()->getViewer()->getIdentity(),
                'gateway_id' => $gateway->gateway_id,
                'state' => 'pending',
                'creation_date' => new Zend_Db_Expr('NOW()'),
                'source_type' => 'talktangle_ads',
                'source_id' => $ads->ad_id,
        ));
        $this->_session->order_id = $order_id = $ordersTable->getAdapter()->lastInsertId();
		
        // Prepare host info
        $schema = 'http://';
        if( !empty($_ENV["HTTPS"]) && 'on' == strtolower($_ENV["HTTPS"]) ) {
            $schema = 'https://';
        }
        $host = $_SERVER['HTTP_HOST'];
        
        
        $params = array();
        $params['language'] = $user->language;
        $localeParts = explode('_', $user->language);
        if( count($localeParts) > 1 ) {
            $params['region'] = $localeParts[1];
        }
        $params['vendor_order_id'] = md5($order_id. $ads->title);
        $params['return_url'] = $schema . $host
                . $this->view->url(array('controller'=>'talktangle','action'=>'paypalreturn', 'module'=>'talktangle'),'default',true)
                . '?order_id=' . $order_id
                . '&state=' . 'return'
                . '&tangle_id='. $tangle->getIdentity()
                . '&type='.$type;
        $params['cancel_url'] = $schema . $host
                . $this->view->url(array('controller'=>'talktangle','action'=>'paypalreturn', 'module'=>'talktangle'),'default',true)
                . '?order_id=' . $order_id
                . '&state=' . 'cancel'
                . '&tangle_id='. $tangle->getIdentity()
                . '&type='.$type;

        //Sell Now Value
        $params['price'] = floatval(5);

        $params['description'] = 'sale';
        $params['amount'] = 1;
        // Process transaction
        $talktangleCore = Engine_Api::_()->talktangle();
        $transaction = $talktangleCore->createBuyNowTransaction($plugin, $ads, $params);
        // Pull transaction params
        $this->view->transactionUrl = $transactionUrl = $plugin->getGateway()->getGatewayUrl();
        $this->view->transactionData = $transactionData = $transaction->getData();
        // Handle redirection
        $transactionUrl .= '?cmd=_express-checkout&token=' . $transactionData['token'];

        // Redirect to paypal
        //return $this->_helper->redirector->gotoUrl($transactionUrl, array('prependBase' => false));
        header("Location: $transactionUrl"); 
    } 
    
    
    public function enableFacebook(){
          $facebookTable = Engine_Api::_()->getDbtable('facebook', 'user');
          $facebookApi = $facebookTable->getApi();
          // Disabled
          if( !$facebookApi ||
              'publish' != Engine_Api::_()->getApi('settings', 'core')->core_facebook_enable ) {
            return false;
          }
          // Not logged in
          if( !$facebookTable->isConnected() ) {
            return false;
          }
          // Not logged into correct facebook account
          if( !$facebookTable->checkConnection() ) {
            return false; 
          }
          
          return true;
    }
    
    public function enableTiwtter(){
          $twitterTable = Engine_Api::_()->getDbtable('twitter', 'user');
          $twitter = $twitterTable->getApi();
        
          // Not connected
          if( !$twitter || !$twitterTable->isConnected() ) {
            return false;
          }
        
          // Disabled
          if( 'publish' != Engine_Api::_()->getApi('settings', 'core')->core_twitter_enable ) {
            return false;
          }
          
          return true;
    }
    
    
}
?>